package com.isaiah.oa.aspect;

import com.isaiah.oa.annotation.DataSource;
import com.isaiah.oa.support.DynamicDataSourceHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;


import java.lang.reflect.Method;

/**
 * 用于主从数据源切换的增强处理类
 * Created by haijun on 2017/12/2.
 */
public class DataSourceAspect {
    /**
     * 在方法执行之前增强
     * @param point
     */
    public void before(JoinPoint point) {
        Object target = point.getTarget();
        String method = point.getSignature().getName();

        Class<?>[] classes = target.getClass().getInterfaces();

        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
                .getMethod().getParameterTypes();
        try {
            Method m = classes[0].getMethod(method, parameterTypes);
            if (m != null && m.isAnnotationPresent(DataSource.class)) {
                // 获取方法上的DataSource注解
                DataSource data = m.getAnnotation(DataSource.class);
                DynamicDataSourceHolder.putDataSource(data.value());
                System.out.println("当前方法使用的是：" +  data.value());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
